package LeetCode.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: leiwenkang
 * @date: 2020/7/11
 * @time: 17:56
 */
public class Test46全排列 {

    public List<List<Integer>> permute(int[] nums) {

        List<List<Integer>> result = new ArrayList<>();

        if (nums == null || nums.length == 0) {
            return result;
        }
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        dfs(nums, 0, used, path, result);

        return result;
    }

    private void dfs(int[] nums, int depth, boolean[] used, List<Integer> path, List<List<Integer>> result) {
        if (depth == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {
                path.add(nums[i]);
                used[i] = true;

                dfs(nums, depth + 1, used, path, result);

                used[i] = false;
                path.remove(path.size() - 1);
            }
        }

    }
}
